package com.chinacreator.galaxylive.utils;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 工具类
 * 
 * @author 敢超
 *
 */
public class ToolUtil {

	private static Logger log = LoggerFactory.getLogger(ToolUtil.class);

	/*
	 * 字符串正则匹配方法(用于匹配字符串是否包含指定字符串)
	 */
	public static boolean stringFilter(String string, String regex) {
		Pattern p = Pattern.compile(regex);
		return p.matcher(string).matches();
	}

	/**
	 * 将http传过来的数据转化成实体
	 * 
	 * @param request
	 * @param clazz
	 * @return
	 */
	public static <T> T getHttpRequestParams(HttpServletRequest request, Class<T> clazz) {
		T bean = null;
		try {
			bean = clazz.newInstance();
			Method[] methods = clazz.getMethods();
			for (Method method : methods) {
				String methodName = method.getName();
				if (methodName.startsWith("set")) {
					String key = methodName.substring(3);
					key = key.substring(0, 1).toLowerCase() + key.substring(1);
					String value = request.getParameter(key);
					if (value != null) {
						method.invoke(bean, value);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bean;
	}

	/**
	 * 实体转json字符串
	 * @param obj
	 * @return
	 */
	public static String objToJson(Object obj) {
//		GsonBuilder gb = new GsonBuilder();
//		gb.registerTypeAdapter(Date.class, new JsonDeserializer(){
//			@Override
//			public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
//				return new Date(json.getAsJsonPrimitive().getAsLong());
//			}
//		}).setDateFormat(DateFormat.LONG);
//		gb.registerTypeAdapter(Date.class, new JsonSerializer<Date>(){
//			@Override
//			public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
//				return new JsonPrimitive(src.getTime());
//			}
//		}).setDateFormat(DateFormat.LONG);
//
//		gb.registerTypeAdapter(java.sql.Date.class, new JsonDeserializer(){
//			@Override
//			public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
//				return new Date(json.getAsJsonPrimitive().getAsLong());
//			}
//		}).setDateFormat(DateFormat.LONG);
//		gb.registerTypeAdapter(java.sql.Date.class, new JsonSerializer<java.sql.Date>(){
//			@Override
//			public JsonElement serialize(java.sql.Date src, Type typeOfSrc, JsonSerializationContext context) {
//				return new JsonPrimitive(src.getTime());
//			}
//		}).setDateFormat(DateFormat.LONG);
//		Gson gson = gb.create();
//		return gson.toJson(obj);
		return JSONObject.toJSONString(obj);
	}

	/**
	 * json字符串转对象
	 * @param json  json格式的字符串
	 * @param clazz
	 * @return
	 */
	public static <T> T jsonToObject(String json, Class<T> clazz) {
	//	return new Gson().fromJson(json, clazz);
		return JSONObject.parseObject(json,clazz);
	}
	
	/**
	 * json转list对象
	 * @param json
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> jsonToList(String json,Class<?> clazz){
		return (List<T>) JSONObject.parseArray(json, clazz);
	}

	/**
	 * map 对象转bean对象 用于统一处理接口输入参数
	 * @param map
	 * @param clazz
	 * @param isUpper Map的key值是否为大写类型 ture: USER_ID,false:userId
	 * @return
	 */
	public static <T> T mapToBean(Map map, Class<T> clazz, boolean isUpper) {
		T t = null;
		try {
			t = clazz.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (map.containsKey(key)) {
                    Object value = map.get(key);
                    Method setter = property.getWriteMethod();
                    if(value.getClass().equals(setter.getParameterTypes()[0])){
						setter.invoke(t, value);
					}else {
						log.warn("【mapToBean】"+key+" 类型不匹配，没有转化");
					}
                }
            }

        } catch (Exception e) {
        	e.printStackTrace();
        }
        return t;
	}

	/**
	 * 大写字母转小写
	 * @param str USER_ID 转小写 userId
	 * @return
	 */
	public static String strToLowerCase(String str) {
		String s1 = str.toLowerCase();
		if (s1.indexOf("_") != -1) {
			StringBuffer sb = new StringBuffer();
			String[] strs = s1.split("_");
			for (String temp : strs) {
				if (sb.length() == 0) {
					sb.append(temp);
				} else {
					char[] cs = temp.toCharArray();
					cs[0] -= 32;
					sb.append(String.valueOf(cs));
				}
			}
			s1 = sb.toString();
		}
		return s1;
	}

	/**
	 * list对象转换成Map<String,Bean>
	 * @param list 对象
	 * @param clazz
	 * @param name 作为map的key的 属性
	 * @return
	 */
	public static <T> Map<String, T> listToMap(List<T> list, Class<T> clazz, String name) {
		HashMap<String, T> map = new HashMap<>();
		char[] cs = name.toCharArray();
		cs[0] -= 32;
		String getMethod = "get" + String.valueOf(cs);
		try {
			Method method = clazz.getMethod(getMethod);
			for (T object : list) {
				String str = (String) method.invoke(object);
				map.put(str, object);
			}
		} catch (Exception e) {
			log.error("listToMap 数据转换出错！");
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * list对象转换成Map<String,String>
	 * 
	 * @param list
	 *            对象
	 * @param clazz
	 * @param name
	 *            作为map的key的 属性
	 * @return
	 */
	public static <T> Map<String, String> listToStrMap(List<T> list, Class<T> clazz, String name) {
		HashMap<String, String> map = new HashMap<>();
		char[] cs = name.toCharArray();
		cs[0] -= 32;
		String getMethod = "get" + String.valueOf(cs);
		try {
			Method method = clazz.getMethod(getMethod);
			for (T object : list) {
				String str = (String) method.invoke(object);
				map.put(str, str);
			}
		} catch (Exception e) {
			log.error("listToMap 数据转换出错！");
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 打印异常堆栈
	 * @param e
	 * @return
	 */
	public static String printExceptionDetail(Exception e){
		String result = "";
		StringWriter sw = null;
		PrintWriter pw = null;
		try {
			sw = new StringWriter();
			pw =  new PrintWriter(sw);
			//将出错的栈信息输出到printWriter中
			e.printStackTrace(pw);
			pw.flush();
			sw.flush();
			result = sw.toString();
		} finally {
			if (sw != null) {
				try {
					sw.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (pw != null) {
				pw.close();
			}
		}
		return result;
	}

	/**
	 * 复制bean属性
	 * @param source
	 * @param type
	 * @param <T>
	 * @return
	 */
	public static <T> T copyBeanProperties(Object source,Class<T> type){
		try {
			T t = type.newInstance();
			PropertyUtils.copyProperties(t,source);
			return t;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
